package com.ItWaVel.controller;

import com.Emplyment.result.Result;
import com.Emplyment.util.AliPay;
import com.Emplyment.vo.PayResultVo;
import com.ItWaVel.config.AlipayProperties;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.itWaVel.feign.client.TemplateClient;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/alipay")
public class AlipayController {

    @Autowired
    private AlipayProperties alipayProperties;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private TemplateClient memberCenterClient;

    @GetMapping("/success")
    public String success(HttpServletRequest request){
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
            // System.out.println(name + " = " + request.getParameter(name));
        }
        System.out.println("=========支付宝同步回调========");
        try {
            boolean checkKey = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(),
                    alipayProperties.getCharset(), alipayProperties.getSignType());
            Assert.isTrue(checkKey, "签名验证失败");
            return "success";
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/notify")
    public Result<String> notifyUrl(HttpServletRequest request){
        String tradeStatus = request.getParameter("trade_status");
        log.info("支付宝异步通知trade_status={}", tradeStatus);
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }

            try {
                boolean checkKey = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(),
                        alipayProperties.getCharset(), alipayProperties.getSignType());
                Assert.isTrue(checkKey, "签名验证失败");

                String out_trade_no = params.get("out_trade_no");
                String alipayTradeNo = params.get("trade_no");
                String totalAmount = params.get("total_amount");
                String subejct = params.get("subject");


                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                BigDecimal amount = new BigDecimal(totalAmount);

                // 更新订单状态
                PayResultVo payResultVo = PayResultVo.builder()
                        .outTradeNo(out_trade_no)
                        .tradeNo(alipayTradeNo)
                        .totalAmount(amount)
                        .subject(subejct)
                        .username(out_trade_no)
                        .build();


                Result result = memberCenterClient.paySuccess(payResultVo);
                Assert.isTrue((boolean) result.getData(), "更新订单状态失败");

            } catch (AlipayApiException e) {
                throw new RuntimeException(e);
            }
            // 更新订单状态
            return Result.success("success");
        }
            return Result.error("error");
    }

    @PostMapping("/prepay")
    public Result<String> prepay(@RequestBody AliPay aliPay){

        // 构造请求参数以调用接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();

        request.setNotifyUrl(alipayProperties.getNotifyUrl());
        request.setReturnUrl(alipayProperties.getReturnUrl());

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", aliPay.getOut_trade_no());
        bizContent.put("total_amount", aliPay.getTotal_amount());
        bizContent.put("subject", aliPay.getSubject());
        bizContent.put("body", aliPay.getBody());
        bizContent.put("product_code", aliPay.getProduct_code());

        request.setBizContent(bizContent.toString());

        try {
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if (response.isSuccess()) {
                String body = response.getBody();
                return Result.success(body);
            }
            return Result.error(response.getMsg());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

         return Result.error("error");

    }

}
